package com.elite.controller;

import com.elite.security.web.RouterSingleFilterChain;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

/**
 * @description:
 * @Author 万伟焕
 * @Date 2024-01-29 15:24:36
 **/
@RestController
public class DemoController implements ApplicationContextAware {

	@Autowired
	private RouterSingleFilterChain routerSingleFilterChain;
	private ApplicationContext applicationContext;
	@GetMapping("/demo")
	public String demo() throws Exception {

		return "demo Spring Security";
	}


	@GetMapping("/closeDemo")
	public String closeDemo() throws Exception {
		HttpSecurity security = applicationContext.getBean(HttpSecurity.class);

		AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry authorizationManagerRequestMatcherRegistry = security.authorizeHttpRequests();
		authorizationManagerRequestMatcherRegistry.requestMatchers("/openDemo","/closeDemo").permitAll();
		authorizationManagerRequestMatcherRegistry.anyRequest().authenticated();

		DefaultSecurityFilterChain filterChain = security.build();

		routerSingleFilterChain.setSecurityFilterChain(Arrays.asList(filterChain));
		return "closeDemo Spring Security";
	}



	@GetMapping("/openDemo")
	public String openDemo() throws Exception {
		HttpSecurity security = applicationContext.getBean(HttpSecurity.class);

		AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry authorizationManagerRequestMatcherRegistry = security.authorizeHttpRequests();
		authorizationManagerRequestMatcherRegistry.requestMatchers("/dome","openDemo","/closeDemo").permitAll();
		DefaultSecurityFilterChain filterChain = security.build();
		routerSingleFilterChain.setSecurityFilterChain(Arrays.asList(filterChain));
		return "openDemo Spring Security";
	}

	@GetMapping("/demo/security")
	public String helloSecurity() {
		return "demo Spring Security";
	}


	@GetMapping("/demo/buildSecurityFilterChain")
	public String build() {
		return "demo Spring Security";
	}




	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext =applicationContext;
	}
}
